// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import FastClick from 'fastclick'
import router from './router'
import store from './vuex'
import { sync } from 'vuex-router-sync'
import './styles/common/reset.css'
import './styles/common/weui.css'
import VueAwesomeSwiper from 'vue-awesome-swiper'
import { InfiniteScroll, Toast } from 'mint-ui';
import * as api from 'api';
Vue.use(InfiniteScroll);
Vue.config.productionTip = false;
Vue.use(VueAwesomeSwiper);

Vue.prototype.title = (title) => {
  document.querySelector('title').innerHTML = title;
};

// simple history management
const history = window.sessionStorage;
history.clear();
let historyCount = history.getItem('count') * 1 || 0;
history.setItem('/', 0);
store.registerModule('V', {
  state: {
    demoScrollTop: 0,
    isLoading: false,
    direction: 'forward'
  },
  mutations: {
    updateDemoPosition (state, payload) {
      state.demoScrollTop = payload.top
    },
    updateLoadingStatus (state, payload) {
      state.isLoading = payload.isLoading
    },
    updateDirection (state, payload) {
      state.direction = payload.direction
    }
  },
  actions: {
    updateDemoPosition ({ commit }, top) {
      commit({ type: 'updateDemoPosition', top: top })
    }
  }
});

let openId = '';
router.beforeEach(function (to, from, next) {
  if (to.name === 'selectProgram') {
    store.dispatch('updateOpenId', to.query.openId)
  } else if (to.name === 'choose') {
    let params = to.params.params.split('&');
    openId = params[0];
    store.dispatch('updateOpenId', openId);
  } else {
    if (to.params.openId) {
      openId = to.params.openId;
      store.dispatch('updateOpenId', to.params.openId)
    }
  }

  store.commit('updateLoadingStatus', { isLoading: true });

  const toIndex = history.getItem(to.path);
  const fromIndex = history.getItem(from.path);

  if (toIndex) {
    if (!fromIndex || parseInt(toIndex, 10) > parseInt(fromIndex, 10) || (toIndex === '0' && fromIndex === '0')) {
      store.commit('updateDirection', { direction: 'forward' })
    } else {
      store.commit('updateDirection', { direction: 'reverse' })
    }
  } else {
    ++historyCount
    history.setItem('count', historyCount)
    to.path !== '/' && history.setItem(to.path, historyCount)
    store.commit('updateDirection', { direction: 'forward' })
  }
  // console.log(/\/http/.test(to.path))
  if (/\/http/.test(to.path)) {
    const url = to.path.split('http')[1]
    window.location.href = `http${url}`
  } else {
    next()
  }
})
router.afterEach(function (to) {
  store.commit('updateLoadingStatus', { isLoading: false })
})

// 摄入路由
sync(store, router)

// 获取jssdk配置
api.getWxConfig()
  .then(res => {
    return new Promise(function (resove, reject) {
      resove(JSON.parse(res.resultData));
    })
  })
  .then(res => {
    wx.config({
      'appId': res.appId,
      'jsApiList': [
        'scanQRCode',
        'chooseWXPay',
        'getLocation'
      ],
      'nonceStr': res.nonceStr,
      'signature': res.signature,
      'timestamp': res.timestamp
    })
  })
  .catch(err => {
    console.log(err);
  });

// 消除300毫秒延迟
FastClick.attach(document.body)
Vue.prototype.Toast = (message, duration = 800, position = 'middle') => {
  Toast({
    message,
    duration,
    position
  })
};
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  created () {
    store.dispatch('getUserId')
// 获取用户信息, 以及运营商金额
    store.dispatch('getUserInfo')
      .then(id => {
        store.dispatch('updateAmount')
      })
  },
  template: '<App/>',
  components: { App }
})
